/**
 * 初始化茶叶档案详情对话框
 */
var TeaFileInfoDlg = {
    teaFileInfoData: {},
    editor: "",
    validateFields: {
        name: {
            validators: {
                notEmpty: {
                    message: '茶叶名称不能为空'
                }
            }
        },
        expiryDay: {
            validators: {
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '只能是数字,例如 180'
                }
            }
        },
        weight: {
            validators: {
                regexp: {
                    regexp: /^[0-9]*$/,
                    message: '只能是数字,例如 250'
                }
            }
        }
    }
};

/**
 * 收集数据
 */
TeaFileInfoDlg.collectData = function () {
    this
        .set('id')
        .set('code')
        .set('name')
        .set('price')
        .set('brewsId')
        .set('productionDate')
        .set('expiryDay')
        .set('shopUrl')
        .set('type')
        .set('technology')
        .set('weight')
        .set('storageMethod')
        .set('packingType')
        .set('packingMethod')
        .set('packingDate')
        .set('updateDate')
        .set('effectIntroduce')
        .set('brandIntroduce')
        .set('processMethod')
        .set('produceLicense')
    ;
};

/**
 * 清除数据
 */
TeaFileInfoDlg.clearData = function () {
    this.teaFileInfoData = {};
}


/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
TeaFileInfoDlg.set = function (key, val) {
    if (!val) {
        //判断选择框是否选择了“其它”
        var val = $('#' + key + 'Other').val();
        if (val) {
            this.teaFileInfoData[key] = val;
        } else {
            this.teaFileInfoData[key] = $("#" + key).val();
        }
        //判断“保存天数”字段是否勾选长期保存
        if (key == 'expiryDay' && $('#expiryDayCheckbox').attr('checked')) {
            this.teaFileInfoData[key] = $("#expiryDayCheckbox").val();
        }
        //存储方法
        if (key == 'storageMethod' && $("#storageMethod").val() != null) {
            if ($("#storageMethod").val() != null) {
                this.teaFileInfoData[key] = $("#storageMethod").val().join(",");
            } else {
                this.teaFileInfoData[key] = "";
            }
        }
    } else {
        this.teaFileInfoData[key] = val;
    }
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
TeaFileInfoDlg.get = function (key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
TeaFileInfoDlg.close = function () {
    parent.layer.close(window.parent.TeaFile.layerIndex);
}

/**
 * 验证表单数据是否为空
 */

TeaFileInfoDlg.validate = function () {
    //校验“价格”字段是否输入的纯数字，判断正整数 /^[1-9]+[0-9]*]*$/
    var re = /^[0-9]+.?[0-9]*$/;
    var priceVal = $('#price').val();
    if (!re.test(priceVal)) {
        alert("价格字段只能输入数字！");
        return false;
    }
    $('#teaInfoForm').data("bootstrapValidator").resetForm();
    $('#teaInfoForm').bootstrapValidator('validate');
    return $("#teaInfoForm").data('bootstrapValidator').isValid();
};


TeaFileInfoDlg.collectDetail = function () {
    this.teaFileInfoData['details'] = TeaFileInfoDlg.editor.txt.html();
    this.set('id').set('title');
};

/**
 * 获取产地下拉框的数据
 */
function getAddress() {
    var address = '其它';
    if ($("#address_prov").val() == "其它") {
        address = $("#addressOther").val();
    } else if ($("#address_prov").val() == "国外") {
        address = $("#address_prov").val();
    } else {
        address = $("#address_prov").val() + "," + $("#address_city").val();
    }
    return address;
}


/**
 * 提交添加
 */
TeaFileInfoDlg.addSubmit = function () {
    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/teaFile/add", function (tea) {
        TeaFileInfoDlg.selector(tea.id);
        window.parent.TeaFile.table.refresh();
        TeaFileInfoDlg.close();
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.teaFileInfoData);
    //设置产地字段信息
    ajax.set("address", getAddress());
    ajax.start();
}

/**
 * 关联图片
 */
TeaFileInfoDlg.selector = function (teaId) {
    //关联之前取消历史关联的图片
    TeaFileInfoDlg.cancelSelector();

    //获得选中的图片
    for (var i = 0; i < 15; i++) {
        var selId = $('#img' + i).attr('selId');
        var label;
        var beginNum;
        if (i < 5) {
            label = '茶叶介绍';
            beginNum = 0;
        } else if (i >= 5 && i < 10) {
            label = '品牌介绍';
            beginNum = 5;
        } else if (i >= 10 && i < 15) {
            label = '产品包装';
            beginNum = 10;
        }
        if (selId) {
            var ajax = new $ax(Feng.ctxPath + "/teaFile/selector", function (data) {
                Feng.success("添加成功!");
            }, function (data) {
                Feng.error("关联图片失败!" + data.responseJSON.message + "!");
            });
            //冲泡方式的id
            ajax.set("teaId", teaId);
            ajax.set("label", label);
            ajax.set("sequence", i - beginNum);
            ajax.set("pictureId", selId);
            ajax.start();
        }
    }
};

/**
 * 取消之前关联的图片
 */
TeaFileInfoDlg.cancelSelector = function () {
    var ajax = new $ax(Feng.ctxPath + "/picture/cancelSelector", function (data) {
        console.log("取消关联成功");
    }, function () {
        console.log("取消关联失败");
    });
    ajax.set("type", "tea");
    ajax.set("itemId", $("#id").val());
    ajax.start();
}

/**
 * 提交修改
 */
TeaFileInfoDlg.editSubmit = function () {
    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/teaFile/update", function (data) {
        TeaFileInfoDlg.selector(TeaFileInfoDlg.teaFileInfoData.id)
        Feng.success("修改成功!");
        window.parent.TeaFile.table.refresh();
        TeaFileInfoDlg.close();
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.teaFileInfoData);
    //设置产地字段信息
    ajax.set("address", getAddress());
    ajax.start();
}

/**
 * 提交编辑更多详情
 */
TeaFileInfoDlg.editDetails = function () {
    this.clearData();
    this.collectDetail();

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/teaFile/editDetail", function (data) {
        Feng.success("修改成功!");
        window.parent.TeaFile.table.refresh();
        TeaFileInfoDlg.close();
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set("details", TeaFileInfoDlg.editor.txt.html().toString());
    ajax.set(this.teaFileInfoData);
    ajax.start();
};


/**
 * 打开图片选择框
 */
TeaFileInfoDlg.openPictureSelector = function (label) {
    //判断是新增页面还是编辑页面
    var teaId = $('#id').val();
    var content = Feng.ctxPath + '/teaFile/tea_picture?teaId=' + teaId + "&label=" + label;
    //得到冲泡方式的id
    var index = layer.open({
        type: 2,
        title: '选择关联图片',
        area: ['1300px', '620px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: content
    });
    this.layerIndex = index;
};

/**
 * 绑定选择框点选“其它”时的输入操作
 * selectIds 需要绑定操作的select元素id
 */
TeaFileInfoDlg.changeSelectOther = function (id) {
    var selVal = $('#' + id).val();
    if (selVal == '其它') {
        $('#' + id + 'Other').css('display', 'block');
        $('#' + id + 'Other').attr('disabled', false);
    } else {
        $('#' + id + 'Other').css('display', 'none');
        $('#' + id + 'Other').attr('disabled', true);
        $('#' + id + 'Other').attr('value', '');
    }
};

/**
 * 初始化checkbox选中状态
 */
TeaFileInfoDlg.changeCheckbox = function () {
    if ($('#expiryDayCheckbox').is(":checked")) {
        $('#expiryDay').attr('value', '-1');
        $('#expiryDay').attr('disabled', true);
    } else {
        $('#expiryDay').attr('value', '');
        $('#expiryDay').attr('disabled', false);
    }
}

/**
 * 选择框加载数据后默认选择
 */
TeaFileInfoDlg.initSelect = function () {
    $("select").each(function () {
        var selectItem = $(this);
        var defaultVale = selectItem.attr('value');
        if (defaultVale) {
            var flag = false;
            //遍历select的所有option选项
            $('.' + selectItem.attr('id')).each(function (i) {
                if (defaultVale == $(this).attr('value')) {
                    flag = false;
                    return false;
                } else {
                    flag = true;
                }
            });
            if (flag) {
                $(this).find("option:contains(其它)").attr("selected", true);
                $('#' + selectItem.attr('id') + 'Other').css('display', 'block');
                $('#' + selectItem.attr('id') + 'Other').attr('disabled', false);
            } else {
                $(this).find("option:contains(" + defaultVale + ")").attr("selected", true);
            }
        }
    });
    //初始化“存储方法”
    $('.selectpicker').selectpicker({
        style: 'btn-info',
        size: 5
    });
    var selValue = $('#storageMethod').attr("value");
    if (selValue && selValue.length > 0) {
        selValue = selValue.split(",");
        $('.selectpicker').selectpicker('val', selValue);
    }
}


$(function () {
    //判断打开的是修改框还是详情编辑窗口
    var E = window.wangEditor;
    if (E) {
        //初始化富文本框编辑器
        var editor = new E('#editor');
        //设置图片的上传地址
        editor.customConfig.debug = true;
        //以base64的格式存储
        editor.customConfig.uploadImgShowBase64 = true;
        //以文件形式上传到服务器
        //editor.customConfig.uploadFileName = 'file';
        //editor.customConfig.uploadImgServer = '/picture/upload';
        editor.create();
        //编辑框宽度设置
        $(".w-e-text-container").css("height", "500px");
        //编辑框全屏按钮(max-height和『全屏』功能一起使用时，会出现一些问题)
        //E.fullscreen.init('#editor');
        editor.txt.html($("#details").html());
        TeaFileInfoDlg.editor = editor;

    } else {
        Feng.initValidator("teaInfoForm", TeaFileInfoDlg.validateFields);
        //（产地）省市互联下拉框初始化
        var addressDiv = $("#address");
        //选择框加载数据后默认选择
        TeaFileInfoDlg.initSelect();
        //默认产地
        var address_prov = "广东";
        var address_city = "东莞";
        var address = addressDiv.attr("address");
        if (address != null && address.indexOf(',') > -1) {
            address = address.split(",");
            address_prov = address[0];
            address_city = address[1];
        } else {
            address_prov = '其它';
            // address_city = '其它';
            $('#addressOther').attr('disabled', false);
            $('#addressOther').css('display', 'block');
        }
        addressDiv.citySelect({
            prov: address_prov,
            city: address_city
        });
    }


});
